package leetcode;

import java.util.ArrayList;
import java.util.List;

/**
 * @Project : AlgorithmLearning
 * @Package : Leetcode
 * @File : Q0394.java
 * @Author : WangRuoyu
 * @Date 2023/11/16 21:36
 */


public class Q0394 {
    public String decodeString(String s) {
        List<StringBuilder> sbList = new ArrayList<>();
        sbList.add(new StringBuilder());
        List<Integer> numList = new ArrayList<>();

        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) >= '0' && s.charAt(i) <= '9') {
                int num = 0;
                int j = i;
                while (s.charAt(j) >= '0' && s.charAt(j) <= '9') {
                    num = num * 10 + s.charAt(j) - '0';
                    j++;
                }
                numList.add(num);
                i = j - 1;
            } else if (s.charAt(i) == '[') {
                sbList.add(new StringBuilder());
            } else if (s.charAt(i) == ']') {
                int num = numList.remove(numList.size() - 1);
                StringBuilder tmp = sbList.remove(sbList.size() - 1);
                StringBuilder sb = new StringBuilder();
                while (num-- > 0) {
                    sb.append(tmp);
                }
                sbList.get(sbList.size() - 1).append(sb);
            } else {
                sbList.get(sbList.size() - 1).append(s.charAt(i));
            }
        }
        return sbList.get(0).toString();
    }

    public static void main(String[] args) {
        Q0394 sl = new Q0394();
    }
}